package com.dayuanit.dy16.pay.alipayspringbootautoconfiguation.handler;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dayuanit.dy16.pay.alipayspringbootautoconfiguation.config.AlipayOrderResult;

import java.util.Map;

public class AlipayHandler {
    private String appid;
    private String alipayServerGatewayUrl;
    private String merchantPrivateKey;
    private String charset;
    private String alipayPublicKey;
    private String signType;
    private String returnUrl;
    private String notifyUrl;

    /**
     *  创建收银台form表单
     */
    public String createPayRequestForm(String orderId) {
        AlipayClient alipayClient =  new DefaultAlipayClient( alipayServerGatewayUrl ,
                appid,
                merchantPrivateKey,
                "JSON",
                charset,
                alipayPublicKey,
                signType);  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request

        alipayRequest.setReturnUrl( returnUrl );
        alipayRequest.setNotifyUrl( notifyUrl ); //在公共参数中设置回跳和通知地址

        alipayRequest.setBizContent( "{"  +
                "    \"out_trade_no\":\""+orderId+"\","  +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
                "\"total_amount\":\"0.10\"," +
                "    \"subject\":\"大猿书城\""  +
                "  }" ); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
            System.out.println("form=" + form);
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }

        return form;
    }

    /**
     * 处理异步通知
     */
    public AlipayOrderResult processNotify(Map<String, String> notifyParamter) {
        // 请求的来源（通过非对称加密RSA搞定 也就是验签名）
        //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(notifyParamter,
                    alipayPublicKey, charset,
                    signType);
            if(!signVerified){
                return AlipayOrderResult.fail("阿里异步通知验签失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return AlipayOrderResult.fail(e.getMessage());
        }

        // 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
        String outTradeNo = notifyParamter.get("out_trade_no");
        String totalAmount = notifyParamter.get("total_amount");
        String appId = notifyParamter.get("app_id");
        String tradeStatus = notifyParamter.get("trade_status");

        //校验交易状态
        if (!"TRADE_SUCCESS".equals(tradeStatus)) {
            return AlipayOrderResult.fail("订单处理失败");
        }

        //校验APPID
        if (!this.appid.equals(appId)) {
            return AlipayOrderResult.fail("appId不正确");
        }

        return AlipayOrderResult.success(totalAmount, outTradeNo);
    }

    /**
     * 查询订单
     */
    public void queryOrder() {

    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public void setAlipayServerGatewayUrl(String alipayServerGatewayUrl) {
        this.alipayServerGatewayUrl = alipayServerGatewayUrl;
    }

    public void setMerchantPrivateKey(String merchantPrivateKey) {
        this.merchantPrivateKey = merchantPrivateKey;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public void setAlipayPublicKey(String alipayPublicKey) {
        this.alipayPublicKey = alipayPublicKey;
    }

    public void setSignType(String signType) {
        this.signType = signType;
    }

    public void setReturnUrl(String returnUrl) {
        this.returnUrl = returnUrl;
    }

    public void setNotifyUrl(String notifyUrl) {
        this.notifyUrl = notifyUrl;
    }
}
